import { computed, ref, Ref, watch, watchEffect } from 'vue'
import { TotalData, NumData, Num, SexIem } from '../types'

/**
 * 预警性别分布
 */
export function useSex({ numData }: { numData: Ref<NumData | null> }) {
  const boyList = ref<SexIem[]>([])
  const girlList = ref<SexIem[]>([])
  const levelDictValueData = ref<string[]>([])

  const handleWatchNumData = () => {
    const numList = numData.value?.levelSexNum
    if (!Array.isArray(numList)) {
      return
    }

    const levelData = numData.value?.levelData

    if (!Array.isArray(levelData) || levelData.length === 0) {
      return
    }

    boyList.value = []
    girlList.value = []

    levelDictValueData.value = []
    let sexObj: any[][] = []
    const sexObj2: any[][] = []
    for (let zz = 0; zz < levelData.length; zz++) {
      sexObj.push([])
      sexObj2.push([])
      let data = [
        {
          level: zz + 1,
          num: 0,
          code: 1,
        },
        {
          level: zz + 1,
          num: 0,
          code: 2,
        },
      ]
      sexObj2[zz] = [...data]
      levelDictValueData.value.push(levelData[zz].dictValue)
    }

    if (numData.value?.levelSexNum.length == 12) {
      numData.value?.levelSexNum.map((item) => {
        if (item.level) sexObj[item.level - 1].push(item)
      })
    } else {
      numData.value?.levelSexNum.map((item) => {
        sexObj2[item.level - 1].map((item2) => {
          if (item2.code == item.code) item2.num = item.num
          return item2
        })
      })
      sexObj = sexObj2
    }

    sexObj.map((vv) => {
      vv.map((item) => {
        if (item.code == '1') {
          boyList.value.push({
            value: item.num,
            level: item.level + '',
            code: item.code + '',
          })
        } else if (item.code == '2') {
          girlList.value.push({
            value: item.num,
            level: item.level + '',
            code: item.code + '',
          })
        }
      })
    })
  }

  watchEffect(handleWatchNumData)

  return {
    boyList,
    girlList,
    levelDictValueData,
  }
}
